import axios from 'axios'
import api from '../api'
import userModel from './data/userModel'
import productModel from './data/productModel'
import cartModel from './data/cartModel'
import orderModel from './data/orderModel'

import MockAdapter from 'axios-mock-adapter'

const mockUserToken = 'user_Token'
const mockUsername = 'admin'
const mockPassword = '123456'

const isLogged = (config, redirect = '') => {
  const result = {
    valid: false,
    response: null
  }

  if (config.headers.token && config.headers.token === mockUserToken) {
    result.valid = true
  }

  if (redirect !== '') {
    result.response = [
      200,
      {
        code: '4003', // 登录后需要重定向
        msg: redirect
      }
    ]
  } else {
    result.response = [
      200,
      {
        code: '4002', // 需要重新
        msg: '登录失效，请重新登录'
      }
    ]
  }

  return result
}

export default {
  init () {
    const mock = new MockAdapter(axios, { delayResponse: 700 })
    const mockApi = new MockAdapter(api.service, { delayResponse: 700 })

    // mockApi约定格式
    // success时：
    // {
    //     code: '1000',
    //     data: {}
    // }
    // error时:
    // {
    //     code: error_code,
    //     msg: error_msg
    // }

    // 登录饥饿
    // 模拟登录返回token
    // TODO；mock JWT
    // TODO: mock token 过期
    mock.onPost('api/user/login.action').reply(function (config) {
      const formData = config.data
      const username = formData.get('username')
      const password = formData.get('password')

      if (username === mockUsername && password === mockPassword) {
        return [
          200,
          {
            token: mockUserToken,
            expire: 30000
          }
        ]
      } else {
        return [
          200,
          {
            code: '1003',
            msg: '用户名或密码错误'
          }
        ]
      }
    })

    // 登出
    mockApi.onPost('api/user/logout.action').reply(function (config) {
      if (config.headers.token === mockUserToken) {
        return [
          200,
          {
            code: '1000',
            msg: '登出成功'
          }
        ]
      }
    })

    // 用户接口
    // 用户信息
    mockApi.onGet('user/userInfo.action').reply(function (config) {
      const loggedValid = isLogged(config)

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: {
              ...userModel.userInfo
            }
          }
        ]
      } else {
        return loggedValid.response
      }
    })

    // 商品接口
    // 商品列表
    mockApi.onGet('product/productList.action').reply(function (config) {
      const params = config.params

      const listData = productModel.getProductByPage(params)

      return [
        200,
        {
          code: '1000',
          data: {
            ...listData
          }
        }
      ]
    })

    mockApi.onGet('product/query.action').reply(function (config) {
      const params = config.params

      const product = productModel.query(params.id)

      if (product) {
        return [
          200,
          {
            code: '1000',
            data: product
          }
        ]
      } else {
        return [
          200,
          {
            code: '5001',
            msg: '找不到该商品'
          }
        ]
      }
    })

    // 商品详情

    // 购物车接口
    // 购物车添加产品
    mockApi.onPost('cart/add.action').reply(function (config) {
      const loggedValid = isLogged(config, '/cart')

      const result = cartModel.add(JSON.parse(config.data))

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: result
          }
        ]
      } else {
        return loggedValid.response
      }
    })

    // 购物车删除产品
    mockApi.onPost('cart/remove.action').reply(function (config) {
      const loggedValid = isLogged(config, '/cart')

      const data = JSON.parse(config.data)
      const result = cartModel.remove(data.id)

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: result
          }
        ]
      } else {
        return loggedValid.response
      }
    })

    mockApi.onPost('cart/removeSome.action').reply(function (config) {
      const loggedValid = isLogged(config, '/cart')

      const productIds = JSON.parse(config.data)
      const result = cartModel.removeSome(productIds)

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: result
          }
        ]
      } else {
        return loggedValid.response
      }
    })

    // 购物车查询
    mockApi.onPost('cart/query.action').reply(function (config) {
      const loggedValid = isLogged(config, '/cart')

      const result = cartModel.query()

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: {
              cart: result
            }
          }
        ]
      } else {
        return loggedValid.response
      }
    })

    // 订单接口
    // 设置预览订单
    mockApi.onPost('order/previewOrder.action').reply(function (config) {
      const loggedValid = isLogged(config, '/order/previewOrder')

      const data = config.data ? JSON.parse(config.data) : {}

      const result = orderModel.setPreviewOrder(data.products)

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: result
          }
        ]
      } else {
        return loggedValid.response
      }
    })

    // 获取预览订单
    mockApi.onGet('order/getPreviewOrder.action').reply(function (config) {
      const loggedValid = isLogged(config, '/cart')

      const result = orderModel.getPreviewOrder()

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: result
          }
        ]
      } else {
        return loggedValid.response
      }
    })

    // 下单接口
    mockApi.onPost('order/submit.action').reply(function (config) {
      const loggedValid = isLogged(config, '/cart')
      const orderId = orderModel.submit(JSON.parse(config.data))

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: {
              orderId: orderId
            }
          }
        ]
      } else {
        return loggedValid.response
      }
    })

    // 订单详情
    mockApi.onGet('order/detail.action').reply(function (config) {
      const loggedValid = isLogged(config, `/order/detail?id=${config.params.id}`)
      const order = orderModel.get(config.params.id)

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: order
          }
        ]
      } else {
        return loggedValid.response
      }
    })

    // 订单列表
    mockApi.onGet('order/list.action').reply(function (config) {
      const loggedValid = isLogged(config, '/order/list')

      const orderList = orderModel.list()

      if (loggedValid.valid) {
        return [
          200,
          {
            code: '1000',
            data: orderList
          }
        ]
      } else {
        return loggedValid.response
      }
    })
  }
}
